package com.medicine.web.controller.manage;

import com.medicine.common.annotation.Log;
import com.medicine.common.core.controller.BaseController;
import com.medicine.common.core.domain.AjaxResult;
import com.medicine.common.core.domain.entity.SysUser;
import com.medicine.common.core.page.TableDataInfo;
import com.medicine.common.enums.BusinessType;
import com.medicine.common.utils.SecurityUtils;
import com.medicine.common.utils.StringUtils;
import com.medicine.manage.service.block.IBlockService;
import com.medicine.system.service.ISysDeptService;
import com.medicine.system.service.ISysPostService;
import com.medicine.system.service.ISysRoleService;
import com.medicine.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/manage/employee")
public class EmployeeController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private IBlockService blockService;


    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
//        startPage();
        List<SysUser> list = userService.selectUserAndRoleList(user);
        return getDataTable(list);
    }



    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
//        deptService.checkDeptDataScope(user.getDeptId());
//        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        int result = userService.insertUser(user);

        try{
            blockService.createEmployeeSignUser(user.getDeptId(), user.getUserId(), user.getUserName());
            return toAjax(result);
        } catch (Exception e){
            return error(e.getMessage());
        }


    }
}
